/**
 * 小林下载工具包 - 内容脚本
 * 用于检测页面上的可下载资源并提供下载功能
 */

// 存储检测到的资源
let detectedResources = {
    videos: [],
    audios: [],
    links: []
};

// 存储设置
let settings = {
    defaultDownloader: 'chrome',
    showPopupOnDownload: true,
    rememberLastPath: true,
    lastSavePath: '',
    fileTypeFilters: {
        videoFiles: true,
        audioFiles: true,
        documentFiles: true,
        archiveFiles: true,
        executableFiles: false,
        imageFiles: true,
        otherFiles: true
    },
    safetySettings: {
        enableSafetyCheck: true,
        blockUnsafeDownloads: false
    }
};

// 文件类型映射
const fileTypeMap = {
    // 视频文件
    'mp4': 'videoFiles',
    'avi': 'videoFiles',
    'mkv': 'videoFiles',
    'flv': 'videoFiles',
    'mov': 'videoFiles',
    'wmv': 'videoFiles',
    'webm': 'videoFiles',
    
    // 音频文件
    'mp3': 'audioFiles',
    'wav': 'audioFiles',
    'flac': 'audioFiles',
    'aac': 'audioFiles',
    'ogg': 'audioFiles',
    
    // 文档文件
    'pdf': 'documentFiles',
    'doc': 'documentFiles',
    'docx': 'documentFiles',
    'xls': 'documentFiles',
    'xlsx': 'documentFiles',
    'ppt': 'documentFiles',
    'pptx': 'documentFiles',
    'txt': 'documentFiles',
    
    // 压缩文件
    'zip': 'archiveFiles',
    'rar': 'archiveFiles',
    '7z': 'archiveFiles',
    'tar': 'archiveFiles',
    'gz': 'archiveFiles',
    
    // 可执行文件
    'exe': 'executableFiles',
    'msi': 'executableFiles',
    'dmg': 'executableFiles',
    'apk': 'executableFiles',
    
    // 图像文件
    'jpg': 'imageFiles',
    'jpeg': 'imageFiles',
    'png': 'imageFiles',
    'gif': 'imageFiles',
    'bmp': 'imageFiles',
    'svg': 'imageFiles',
    'webp': 'imageFiles'
};

// 初始化
function init() {
    // 加载设置
    chrome.storage.sync.get(['settings'], function(result) {
        if (result.settings) {
            settings = result.settings;
        }
        
        // 开始检测资源
        detectResources();
        
        // 监听DOM变化，以检测新添加的资源
        observeDOMChanges();
        
        // 添加右键菜单处理
        setupContextMenuHandler();
    });
    
    // 监听来自扩展的消息
    chrome.runtime.onMessage.addListener(handleMessages);
}

// 检测页面上的资源
function detectResources() {
    // 检测视频
    if (settings.fileTypeFilters.videoFiles) {
        detectVideos();
    }
    
    // 检测音频
    if (settings.fileTypeFilters.audioFiles) {
        detectAudios();
    }
    
    // 检测下载链接
    detectDownloadLinks();
}

// 检测视频资源
function detectVideos() {
    const videos = document.querySelectorAll('video');
    videos.forEach(video => {
        // 避免重复检测
        if (video.dataset.xlDownloadDetected) return;
        
        // 标记为已检测
        video.dataset.xlDownloadDetected = 'true';
        
        // 获取视频源
        const sources = Array.from(video.querySelectorAll('source'))
            .map(source => source.src)
            .filter(src => src);
            
        // 如果没有source标签，尝试直接获取src
        if (sources.length === 0 && video.src) {
            sources.push(video.src);
        }
        
        // 如果找到视频源
        if (sources.length > 0) {
            // 添加到检测列表
            sources.forEach(src => {
                if (!detectedResources.videos.includes(src)) {
                    detectedResources.videos.push(src);
                }
            });
            
            // 添加下载按钮
            addVideoDownloadButton(video, sources);
        }
    });
}

// 检测音频资源
function detectAudios() {
    const audios = document.querySelectorAll('audio');
    audios.forEach(audio => {
        // 避免重复检测
        if (audio.dataset.xlDownloadDetected) return;
        
        // 标记为已检测
        audio.dataset.xlDownloadDetected = 'true';
        
        // 获取音频源
        const sources = Array.from(audio.querySelectorAll('source'))
            .map(source => source.src)
            .filter(src => src);
            
        // 如果没有source标签，尝试直接获取src
        if (sources.length === 0 && audio.src) {
            sources.push(audio.src);
        }
        
        // 如果找到音频源
        if (sources.length > 0) {
            // 添加到检测列表
            sources.forEach(src => {
                if (!detectedResources.audios.includes(src)) {
                    detectedResources.audios.push(src);
                }
            });
            
            // 添加下载按钮
            addAudioDownloadButton(audio, sources);
        }
    });
}

// 检测下载链接
function detectDownloadLinks() {
    const links = document.querySelectorAll('a[href]');
    links.forEach(link => {
        // 避免重复检测
        if (link.dataset.xlDownloadDetected) return;
        
        // 标记为已检测
        link.dataset.xlDownloadDetected = 'true';
        
        const href = link.href;
        
        // 检查是否是文件下载链接
        if (isDownloadLink(href)) {
            // 添加到检测列表
            if (!detectedResources.links.includes(href)) {
                detectedResources.links.push(href);
            }
            
            // 增强下载链接
            enhanceDownloadLink(link, href);
        }
    });
}

// 判断链接是否是下载链接
function isDownloadLink(url) {
    try {
        const urlObj = new URL(url);
        const pathname = urlObj.pathname;
        const extension = pathname.split('.').pop().toLowerCase();
        
        // 检查是否有文件扩展名
        if (extension && fileTypeMap[extension]) {
            // 检查是否启用了该类型的文件过滤
            return settings.fileTypeFilters[fileTypeMap[extension]];
        }
        
        // 检查是否有下载参数
        if (urlObj.searchParams.has('download') || 
            urlObj.searchParams.has('dl') || 
            pathname.includes('download')) {
            return true;
        }
        
        return false;
    } catch (e) {
        return false;
    }
}

// 添加视频下载按钮
function addVideoDownloadButton(videoElement, sources) {
    // 创建下载按钮容器
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'xl-download-button-container';
    buttonContainer.style.cssText = `
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 9999;
        opacity: 0;
        transition: opacity 0.3s;
    `;
    
    // 创建下载按钮
    const downloadButton = document.createElement('button');
    downloadButton.className = 'xl-download-button';
    downloadButton.style.cssText = `
        background-color: rgba(33, 150, 243, 0.8);
        color: white;
        border: none;
        border-radius: 4px;
        padding: 5px 10px;
        font-size: 14px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
    `;
    
    // 添加图标
    downloadButton.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
            <polyline points="7 10 12 15 17 10"></polyline>
            <line x1="12" y1="15" x2="12" y2="3"></line>
        </svg>
        <span style="margin-left: 5px;">下载视频</span>
    `;
    
    // 添加点击事件
    downloadButton.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        // 如果只有一个源，直接下载
        if (sources.length === 1) {
            sendDownloadRequest(sources[0], getFilenameFromURL(sources[0]));
        } else {
            // 如果有多个源，显示选择菜单
            showSourceSelectionMenu(videoElement, sources);
        }
    });
    
    // 添加到容器
    buttonContainer.appendChild(downloadButton);
    
    // 获取视频容器
    let videoContainer = videoElement.parentElement;
    
    // 确保容器有定位属性
    if (getComputedStyle(videoContainer).position === 'static') {
        videoContainer.style.position = 'relative';
    }
    
    // 添加到DOM
    videoContainer.appendChild(buttonContainer);
    
    // 添加鼠标事件
    videoContainer.addEventListener('mouseenter', function() {
        buttonContainer.style.opacity = '1';
    });
    
    videoContainer.addEventListener('mouseleave', function() {
        buttonContainer.style.opacity = '0';
    });
}

// 添加音频下载按钮
function addAudioDownloadButton(audioElement, sources) {
    // 创建下载按钮
    const downloadButton = document.createElement('button');
    downloadButton.className = 'xl-audio-download-button';
    downloadButton.innerHTML = '下载';
    downloadButton.style.cssText = `
        background-color: rgba(156, 39, 176, 0.8);
        color: white;
        border: none;
        border-radius: 4px;
        padding: 2px 8px;
        font-size: 12px;
        cursor: pointer;
        margin-left: 10px;
    `;
    
    // 添加点击事件
    downloadButton.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        // 如果只有一个源，直接下载
        if (sources.length === 1) {
            sendDownloadRequest(sources[0], getFilenameFromURL(sources[0]));
        } else {
            // 如果有多个源，显示选择菜单
            showSourceSelectionMenu(audioElement, sources);
        }
    });
    
    // 添加到DOM
    audioElement.parentElement.insertBefore(downloadButton, audioElement.nextSibling);
}

// 增强下载链接
function enhanceDownloadLink(linkElement, url) {
    // 添加下载图标
    const downloadIcon = document.createElement('span');
    downloadIcon.className = 'xl-download-icon';
    downloadIcon.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-left: 5px; vertical-align: middle;">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
            <polyline points="7 10 12 15 17 10"></polyline>
            <line x1="12" y1="15" x2="12" y2="3"></line>
        </svg>
    `;
    
    // 添加到链接
    linkElement.appendChild(downloadIcon);
    
    // 添加样式
    linkElement.style.cssText += `
        display: inline-flex;
        align-items: center;
    `;
    
    // 添加点击事件
    linkElement.addEventListener('click', function(e) {
        // 如果设置了显示弹窗，则阻止默认行为
        if (settings.showPopupOnDownload) {
            e.preventDefault();
            e.stopPropagation();
            
            // 发送下载请求
            sendDownloadRequest(url, getFilenameFromURL(url));
        }
    });
}

// 显示源选择菜单
function showSourceSelectionMenu(element, sources) {
    // 创建菜单容器
    const menu = document.createElement('div');
    menu.className = 'xl-source-selection-menu';
    menu.style.cssText = `
        position: absolute;
        background-color: white;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        padding: 10px;
        z-index: 10000;
    `;
    
    // 添加标题
    const title = document.createElement('div');
    title.textContent = '选择要下载的源';
    title.style.cssText = `
        font-weight: bold;
        margin-bottom: 10px;
        padding-bottom: 5px;
        border-bottom: 1px solid #eee;
    `;
    menu.appendChild(title);
    
    // 添加源列表
    sources.forEach((src, index) => {
        const sourceItem = document.createElement('div');
        sourceItem.className = 'xl-source-item';
        sourceItem.textContent = `源 ${index + 1}: ${getFilenameFromURL(src)}`;
        sourceItem.style.cssText = `
            padding: 8px;
            cursor: pointer;
            border-radius: 4px;
        `;
        
        // 发送下载请求
        function sendDownloadRequest(url, filename) {
            if (settings.safetySettings.enableSafetyCheck) {
                chrome.runtime.sendMessage({
                    type: 'safety_check',
                    url: url
                }, response => {
                    if (!response.isSafe && settings.safetySettings.blockUnsafeDownloads) {
                        alert('安全检测未通过：' + response.message);
                        return;
                    }
                    initiateDownload(url, filename);
                });
            } else {
                initiateDownload(url, filename);
            }
        }

        // 实际执行下载
        function initiateDownload(url, filename) {
            chrome.runtime.sendMessage({
                type: 'download_file',
                url: url,
                filename: filename,
                savePath: settings.rememberLastPath ? settings.lastSavePath : ''
            }, response => {
                if (response.success) {
                    settings.lastSavePath = response.savePath;
                    chrome.storage.sync.set({ settings });
                } else {
                    alert('下载失败: ' + response.error);
                }
            });
        }

        // 从URL获取文件名
        function getFilenameFromURL(url) {
            try {
                const pathname = new URL(url).pathname;
                return pathname.split('/').pop() || 'download';
            } catch {
                return 'download';
            }
        }

        // 监听DOM变化
        function observeDOMChanges() {
            const observer = new MutationObserver(mutations => {
                mutations.forEach(mutation => {
                    if (mutation.addedNodes.length) {
                        detectResources();
                    }
                });
            });
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        }

        // 设置右键菜单处理
        function setupContextMenuHandler() {
            document.addEventListener('contextmenu', function(e) {
                const selectedText = window.getSelection().toString().trim();
                if (selectedText && isDownloadLink(selectedText)) {
                    chrome.runtime.sendMessage({
                        type: 'show_context_menu',
                        url: selectedText
                    });
                }
            }, false);
        }

        // 处理消息
        function handleMessages(request, sender, sendResponse) {
            if (request.type === 'download_all_videos') {
                detectedResources.videos.forEach(url => {
                    sendDownloadRequest(url, getFilenameFromURL(url));
                });
            }
        }
    });
}